package com.yh.doing.interpret_pattern.demo2;

import java.util.Stack;

/**
 * @program: design-patterns
 * @description:
 * @author: yangh0597@163.com
 * @date: 2022-11-27 14:31
 * @problem:
 **/
public class PCClient {
    //    private String expression;
    private Stack<IExpression> stack = new Stack<IExpression>();

    public PCClient(String expression) {
//        this.expression = expression;
        this.parse(expression);

    }

    private void parse(String expression) {
        String[] expressionList = expression.split(" ");
        IExpression left, right;
        for (int i = 0; i < expressionList.length; i++) {
            String expressionItem = expressionList[i];
            boolean operator = OperatorUtil.isOperator(expressionItem);
            if (operator) {
                left = stack.pop();
                right = new NumTerminalExpression(Integer.valueOf(expressionList[++i]));

                NonTerminalExpression terminalExpression = OperatorUtil.getTerminalExpression(left, right, expressionItem);
                stack.push(terminalExpression);
            } else {
                stack.push(new NumTerminalExpression(Integer.valueOf(expressionItem)));
                System.out.println(expressionItem + "push stack");
            }
        }
    }


    public int calculate() {
        return this.stack.pop().interpret();
    }
}
